import React from 'react';
import {connect} from 'dva'
import moment from 'moment'

import Title from 'components/Title'
import Chart from 'components/Chart'
import Tools from 'utils/tools';

import { config } from 'utils';
const { CMR } = config;
const {
  Token,
  villageList,
} = CMR;

@connect(({watermeter}) => ({...watermeter}))
class Watermeter extends React.Component {
  echartsConf = {
    chart: {
      type: 'Common2',
      color: ['74, 144, 255', '98, 203, 120', '246, 214, 71', '231, 62, 62'],
      other: { showLegend: true },
    },
  };
     
  constructor(props) {
    super(props);

    let time;
    if ('defaultValue' in props) {
      time = props.defaultValue;
    }
    this.state = {
      time,
      monthList: []
    };
  }

  componentDidMount() {
    this.init();
  }

  init = () => {
    const { time } = this.state;
    const monthList = Tools.getFullMonth(time);
    this.setState({
      monthList
    }, () => {
      this.setDateECharts()
    })
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.defaultValue !== nextProps.defaultValue) {
      if (nextProps.defaultValue) {
        this.setState({
          time: nextProps.defaultValue
        }, () => {
          this.init()
        })
      }
    }
  }

  // 图表
  setDateECharts = () => {
    const cm_ids = villageList.map(ele => { return ele.cm_id })
    const server = {
      type: 'watermeter/queryVillageleak',
      payload: {
        Token,
        cm_ids,
        index:1,
        size:10000,
        type: 'StatisticsVillageleak',
      }
    };
    this.queryServer(server);
  }
  // 处理echarts配置请求
  queryServer = async (server) => {
    const { time } = this.state;
    let { payload } = server;
    Object.assign(payload, {
      dateBegin: moment(`${time}-01`).startOf('month').unix(),
      dateEnd: moment(`${time}-12`).endOf('month').unix(),
    })
    Object.assign(server, { payload })
    await this.props.dispatch(server);
  }
 
  getData = (dataResourceArr, seriesItems, monthList) => {
    let result = {}

    let dataArr = [];
    let timeArr = [];
    if(Array.isArray(dataResourceArr) && Array.isArray(seriesItems)){
      seriesItems.map((items,idx) => {
        const curResource = dataResourceArr.filter(resource =>{
          if(items['cm_id'] === resource['cm_id']) return resource;
        })
        const data =[]
        monthList.forEach(ele => {
          // 每月第一天 和 最后一天
          const startTimestamp = moment(moment(ele).startOf('month')).unix();
          const endTimestamp = moment(moment(ele).endOf('month')).unix();
          const supplyData = Tools.SumRange(curResource, 'allv', [startTimestamp, endTimestamp], 'dt')
          const sellData = Tools.SumRange(curResource, 'leakv', [startTimestamp, endTimestamp], 'dt')
          const radio = supplyData === 0 ? 0 :(sellData/supplyData * 100).toFixed(2) * 1;
          data.push(radio)
          // 处理时间
          if(idx === 0) timeArr.push(moment(ele).format('M月'))
        })
        const params = Object.assign(items, { data });
        dataArr.push(params)
      })
    }
    Object.assign(result, {time: timeArr, data: dataArr })
    return result;
  }

  // 图表渲染
  render() {
    const { props, state, echartsConf } = this;
    const { monthList } = state;

    const { type: chartType, color, other } = echartsConf.chart;
    const Resource = this.getData(props['VillageleakResourceStatisticsVillageleak'], villageList, monthList)
    const columns = { yAxis: [{ name: '%'}], seriesItems: villageList }
    return (<Title title={'小区产销差分析'}>
      <Chart
        type={chartType}
        color={color}
        columns={columns}
        dataSource={Resource}
        other = {other}
      />
    </Title>)
  }
}

export default Watermeter;
